package com.orange.common.utils;

import cn.hutool.core.util.ObjectUtil;

import com.orange.common.base.entity.AccessToken;
import com.orange.common.base.entity.AppInfo;
import com.orange.common.base.entity.TokenInfo;
import com.orange.common.base.entity.UserInfo;
import com.orange.common.base.redis.utils.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2022/1/28 10:12
 */
@Component
public final class TokenUtils {

    private final static Logger logger = LoggerFactory.getLogger(TokenUtils.class);

    /**
     * 当前redis缓存实例
     */
    private static TokenUtils instance = new TokenUtils();

    @Autowired
    private RedisCache redisCache;

    /**
     * 该注解被用来修饰一个非静态的void（）方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，
     * 并且只会被服务器执行一次。PostConstruct在构造函数之后执行，init（）方法之前执行。
     *
     * 执行顺序：Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
     */
    @PostConstruct
    public void init(){
        instance.redisCache = redisCache;
    }

    /**
     * 保存token信息
     * @param tokenType
     * @param appInfo
     * @param userInfo
     * @return
     */
    public static AccessToken saveToken(int tokenType, AppInfo appInfo, UserInfo userInfo) {
        final int expireIntTime = 5 * 60 * 60;
        String token = UUID.randomUUID().toString();
        // token有效期为2小时
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND, expireIntTime);
        Date expireTime = calendar.getTime();
        // 4. 保存token
        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setTokenType(tokenType);
        tokenInfo.setAppInfo(appInfo);
        if (tokenType == 1) {
            tokenInfo.setUserInfo(userInfo);
        }
        instance.redisCache.set(token, tokenInfo, expireIntTime, TimeUnit.SECONDS);
        AccessToken accessToken = new AccessToken(token, expireTime);

        return accessToken;
    }

    /**
     * 查询登录用户信息
     * @param token
     * @return
     */
    public static UserInfo getTokenUser(String token){
        UserInfo userInfo = new UserInfo();
        TokenInfo tokenInfo = instance.redisCache.get(token);
        if (ObjectUtil.isNotEmpty(tokenInfo)) {
            if (tokenInfo.getTokenType()==1){
                userInfo = tokenInfo.getUserInfo();
            }else{
                userInfo.setUsername("游客用户");
                userInfo.setEmail("888@xx.com");
            }
        }
        logger.info("userInfo:{}",userInfo);
        return userInfo;
    }

    /**
     * 查询开发者账号信息
     * @param token
     * @return
     */
    public static AppInfo getTokenAppInfo(String token){
        AppInfo appInfo = null;
        TokenInfo tokenInfo = instance.redisCache.get(token);
        if (ObjectUtil.isNotEmpty(tokenInfo)) {
            if (tokenInfo.getTokenType()==1){
                appInfo = tokenInfo.getAppInfo();
            }
        }
        logger.info("appInfo:{}",appInfo);
        return appInfo;
    }

    /**
     * 销毁token
     * @param token
     */
    public static void destoryToken(String token){
        instance.redisCache.delete(token);
    }

}
